# Makefile for HPM56750EVKmini JTAG Debug

# OpenOCD executable
OPENOCD = openocd.exe

# OpenOCD configuration files
PROBE_CFG = board\debug_scripts\openocd\probes\ft2232.cfg
SOC_CFG = board\debug_scripts\openocd\soc\hpm6750-single-core.cfg
BOARD_CFG = board\debug_scripts\openocd\boards\hpm6750evkmini.cfg

# ELF file name
ELF_FILE = rtthread.elf
BIN_FILE = rtthread.bin

# Flash base address (adjust according to your chip's memory map)
FLASH_BASE_ADDR = 0x80000000

# Default target
.PHONY: all
all:
	@echo "Available targets:"
	@echo "  flash     - Flash the firmware to the device with elf file"
	@echo "  flashb     - Flash the firmware to the device with bin file"
	@echo "  debug     - Start debugging session"
	@echo "  reset     - Reset the device"
	@echo "  halt      - Halt the device"
	@echo "  clean     - Clean build files"

# Flash the firmware to the device
.PHONY: flash
flash:
	$(OPENOCD) -f "$(PROBE_CFG)" -f "$(SOC_CFG)" -f "$(BOARD_CFG)" -c "init; halt; flash write_image erase $(ELF_FILE); reset; shutdown"

.PHONY: flashb
flashb:
	$(OPENOCD) -f "$(PROBE_CFG)" -f "$(SOC_CFG)" -f "$(BOARD_CFG)" -c "init; halt; flash write_image erase $(BIN_FILE) $(FLASH_BASE_ADDR) bin; reset; shutdown"


# Start debugging session
.PHONY: debug
debug:
	$(OPENOCD) -f "$(PROBE_CFG)" -f "$(SOC_CFG)" -f "$(BOARD_CFG)" -c "init; halt"

# Reset the device
.PHONY: reset
reset:
	$(OPENOCD) -f "$(PROBE_CFG)" -f "$(SOC_CFG)" -f "$(BOARD_CFG)" -c "init; reset; shutdown"

# Halt the device
.PHONY: halt
halt:
	$(OPENOCD) -f "$(PROBE_CFG)" -f "$(SOC_CFG)" -f "$(BOARD_CFG)" -c "init; halt; shutdown"

# Clean build files
.PHONY: clean
clean:
	@echo "Cleaning build files..."
	# Add your clean commands here

# Show help
.PHONY: help
help:
	@echo "Makefile for HPM5301EVKLite JTAG Debug"
	@echo ""
	@echo "Usage:"
	@echo "  make <target>"
	@echo ""
	@echo "Targets:"
	@echo "  all        - Show available targets"
	@echo "  flash      - Flash the firmware to the device"
	@echo "  flashb     - Flash the firmware to the device with bin file"
	@echo "  debug      - Start debugging session"
	@echo "  reset      - Reset the device"
	@echo "  halt       - Halt the device"
	@echo "  clean      - Clean build files"
	@echo "  help       - Show this help message"


# gdb
GDB_TOOL = "E:/Share/env-windows/riscv32-gnu-toolchain-win-2022.04.12/bin/riscv32-unknown-elf-gdb.exe"
GDB_SCRIPT = gdb_script.cfg
script:
	@echo "target extended-remote :3333" > $(GDB_SCRIPT)
	@echo "monitor reset halt" >> $(GDB_SCRIPT)
	@echo "load" >> $(GDB_SCRIPT)
	@echo "b main" >> $(GDB_SCRIPT)
	@echo "b rt_assert_handler" >> $(GDB_SCRIPT)
	@echo "#info r" >> $(GDB_SCRIPT)

gdb:
	$(GDB_TOOL) $(ELF_FILE) -x $(GDB_SCRIPT)